var rootPath = getRootPath();

$(function() {

	jQuery.validator.addMethod("checkTagName", function(value, element) {
		var oriTagName = $("#oriTagName").val();
		return checkTagName(value,oriTagName);
	}, "标签名称已存在");
	
	$("#tagEditForm").validate({
		rules : {
			tagName :  {
				required : true,
				checkTagName : true
			},
			tagWeight : {
				required : true,
				digits:true,
				range:[0,100000]
			}
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			$.ajax({
				url: rootPath + '/tag/' + $("#tagId").val(),
		        type: 'PUT',
		        data: JSON.stringify($('#tagEditForm').serializeJson()),
	            contentType: 'application/json;charset=UTF-8', 
		        success: function (data) {
					if(data.returnCode == "0000") {						
						layer.msg('成功更新标签!',{icon:1,time:1000},function() {						
							parent.window.location.href = rootPath + '/tagPage';
							var index = parent.layer.getFrameIndex(window.name);
							parent.layer.close(index);
						});
					} else {
						layer.alert(data.returnMessage);
					}
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		        	layer.alert("更新标签失败:(");
		        }
		    });
		}
	});
});

function checkTagName(tagName,oriTagName) {
	var isValidTagName = true;
	if(tagName != oriTagName) {
		$.ajax({
			url: rootPath + '/tag/checkTagName',
	        type: 'GET',
	        async: false,
	        data: {
	        	"tagName" : tagName
	        },
	        success: function (data) {
	        	if(data != "true") {
	        		isValidTagName = false;
	        	}
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	        	layer.alert("error:(");
	        }
	    });
	}
	return isValidTagName;
}